<template>
  <div class="hello">
    <h1>演示 async await 的使用</h1>
    <button @click="threeCallback">3个回调的使用</button>
    <button @click="postParam">post传参</button>
    <button @click="asyncawait">async返回对象结构</button>
    <button @click="asyncError">asyncError</button>
    <button @click="serialReq">串行请求</button>
    <button @click="synchronized">并行请求</button>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import axios from "axios";

export default defineComponent({
  name: "HelloWorld",
  props: {
    msg: String,
  },
  setup() {
    const baseUrl = "api";
    const url_zhihu = `${baseUrl}/cashType/selectAll`; // get 请求
    const url_vue3users = `${baseUrl}/vue3user/selectAll`; // get 请求

    // 5. 并行请求
    const synchronized = async () => {
      console.log(`${new Date()},开始多个请求的串行执行`);
      sleepReq1().then((res) => {
        console.log(`串行第一个请求数据：${res.data}`);
      });

      sleepReq2().then((res) => {
        console.log(`串行第二个请求数据：${res.data}`);
      });
      console.log(`${new Date()},串行请求结束`);
    };

    // 4. 多个请求串行 - 测试失败
    const serialReq = async () => {
      // console.log(`${new Date()},开始多个请求的串行执行`);
      // const res1 = await axios.get(url_zhihu);
      // await sleep();
      // const res2 = await axios.get(url_vue3users);
      // console.log(`${new Date()},串行请求结束`);
    };

    // 3. async 中的错误处理
    const asyncError = async () => {
      let res = null;
      try {
        res = await axios.get(`url_zhihu11`);
      } catch (err) {
        console.log("异步请求出现异常：", err);
      }

      console.log(`响应来的数据是：`, res);
    };

    // async   await 的使用
    // await 返回的对象如下结构，即要获取实际的数据应该：res.data.data
    // 两重 data 才是后端返回的统一接口对象
    // {config:{},data:{code:1,msg:'成功',data:[...]},headers:{},request:{},status:200,statusText:""}
    // 要判断响应有没有出错：res.status !== 200
    const asyncawait = async () => {
      const res = await axios.get(url_zhihu);
      console.log("响应来的数据是：", res.data.data);
    };

    // 2. post 请求传参
    const postParam = () => {
      axios
        .put(`${baseUrl}/cashType/update`, {
          iid: 5,
          sid: "工资1",
        })
        .then((res) => {
          console.log(`修改成功，返回的结果是：`, res);
        });
    };

    // 1. 3个回调的使用方法
    const threeCallback = () => {
      axios
        .get(url_zhihu)
        .then((res) => {
          // 请求成功的回调
          console.log(res);
        })
        .catch((err) => {
          // 请求出现异常的回调
          console.log("请求出现异常");
          console.log(err);
        })
        .then((fin) => {
          // finally 的回调
          console.log("无论成功与否都会执行的");
        });
    };

    // 延迟2秒的自定义方法
    const sleep = (timeout = 2000) =>
      new Promise((resolve) => {
        setTimeout(resolve, timeout);
      });

    // 测试并行、串行请求会用到的请求1
    async function sleepReq1() {
      await sleep(2000);
      return axios.get(url_zhihu);
    }

    // 测试并行、串行请求会用到的请求2
    async function sleepReq2() {
      await sleep(2000);
      return axios.get(url_vue3users);
    }

    return {
      threeCallback,
      postParam,
      asyncawait,
      asyncError,
      serialReq,
      synchronized,
    };
  },
});
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
